﻿using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Task = System.Threading.Tasks.Task;

namespace NFinalCompiler
{
    [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
    [InstalledProductRegistration("My Asynchronous Package", "Loads asynchronously", "1.0")]
    [ProvideService(typeof(NFinalCompilerService), IsAsyncQueryable = true)]
    [ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_string, PackageAutoLoadFlags.BackgroundLoad)]
    [Guid(NFinalCompilerAsyncPackage.PackageGuidString)]
    public class NFinalCompilerAsyncPackage : AsyncPackage
    {
        public const string PackageGuidString = "33cd9153-3847-49d8-b887-823444a2a1c3";

        //private EnvDTE.DTE dte;
        //private Microsoft.VisualStudio.Shell.Interop.IVsOutputWindow output;
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
        {
            // runs in the background thread and doesn't affect the responsiveness of the UI thread.
            //await Task.Delay(5000);

            // Adds a service on the background thread
            //AddService(typeof(NFinalCompilerService), CreateMyServiceAsync);

            //var dte = await GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
            // Switches to the UI thread in order to consume some services used in command initialization
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            var svc = new NFinalCompilerService();
            await svc.InitializeAsync(this, cancellationToken);
            // Query service asynchronously from the UI thread

            //output =(Microsoft.VisualStudio.Shell.Interop
            //    .IVsOutputWindow)await GetServiceAsync(typeof(Microsoft.VisualStudio.Shell.Interop.IVsOutputWindow));
        }

        private async Task<object> CreateMyServiceAsync(IAsyncServiceContainer container, CancellationToken cancellationToken, Type serviceType)
        {
            var svc = new NFinalCompilerService();
            await svc.InitializeAsync(this,cancellationToken);
            return svc;
        }
    }
}
